#ifndef __HELLOWINDOW_H__
#define __HELLOWINDOW_H__

#define WINDOW_WIDTH 800
#define WINDOW_HEIGHT 600

#include <iostream>

#include <glad/glad.h>
#include <GLFW/glfw3.h>

void FramebufferSizeCallback(GLFWwindow* window, int width, int height);
void ProcessInput(GLFWwindow* window);

int main()
{
    glfwInit(); //初始化 glfw

    //配置 glfw
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);  //使用 OpenGL 3.3, glfw 创建上下文时进行调整
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);  //核心渲染模式

    //创建窗口
    GLFWwindow* Window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "LearnOpenGL", NULL, NULL);
    if (Window == NULL)
    {
        std::cout << "Fail to create glfw window" << std::endl;
        glfwTerminate();    //销毁所有 glfw 对象
        return -1;
    }
    glfwMakeContextCurrent(Window); //使指定窗口的上下文为调用线程的当前上下文
    glfwSetFramebufferSizeCallback(Window, FramebufferSizeCallback);    //设置更改窗口大小时回调

    //加载 glad 内容
    //glfwGetProcAddress返回当前上下文的指定函数的地址
    if(!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Fail to initialize GLAD" << std::endl;
        return - 1;
    }

    //通知 OpenGL 渲染窗口的尺寸大小, 将自身坐标(-1 , 1) 映射至 (0, width/ height)
    glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

    //渲染
    while(!glfwWindowShouldClose(Window))   //窗口没退出则会进行渲染
    {
        ProcessInput(Window);

        //渲染指令

        //清除颜色
        glClearColor(0.2f, 0.3f, 0.3f, 1.f);
        glClear(GL_COLOR_BUFFER_BIT);

        glfwSwapBuffers(Window);    //双缓冲
        glfwPollEvents();   //检查输入事件、更新窗口状态
    }

    glfwTerminate();
    return 0;
}

void FramebufferSizeCallback(GLFWwindow* window, int width, int height)
{
    glViewport(0, 0, width, height);
}

void ProcessInput(GLFWwindow* window)
{
    if (glfwGetKey(window, GLFW_KEY_0) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
}

#endif